/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.session;

import com.thienloc.omap.entity.OmapUser;
import com.thienloc.omap.util.Constant;
import com.thienloc.omap.util.SecurityUtil;
import java.util.List;
import org.slf4j.LoggerFactory;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author GiangLT
 */
@Stateless
public class OmapUserFacade extends AbstractFacade<OmapUser> {

    @PersistenceContext(unitName = "omapPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public OmapUserFacade() {
        super(OmapUser.class);
    }

    public OmapUser findByUsernameAndPassword(String username, String password) {
        try {
            TypedQuery<OmapUser> q = em.createNamedQuery("OmapUser.findByUsername", OmapUser.class);
            q.setParameter("username", username);
            OmapUser user = q.getSingleResult();
            if (user != null) {
                boolean equal = SecurityUtil.isMatched(password, user.getPassword(), user.getPasswordSalt(), Constant.PASSWORD_ITERATION_NUM);
                if (equal) {
                    return user;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (NoResultException ex) {
            return null;
        } catch (Exception ex) {
            LoggerFactory.getLogger(OmapUserFacade.class.getName()).error("", ex);
            return null;
        }
    }

    public OmapUser findByUsername(String username) {
        try {
            TypedQuery<OmapUser> q = em.createNamedQuery("OmapUser.findByUsername", OmapUser.class);
            q.setParameter("username", username);
            OmapUser user = q.getSingleResult();
            if (user != null) {
                return user;
            } else {
                return null;
            }
        } catch (NoResultException ex) {
            return null;
        } catch (Exception ex) {
            LoggerFactory.getLogger(OmapUserFacade.class.getName()).error("", ex);
            return null;
        }
    }

    public List<OmapUser> findByRoleName(String roleName) {
        try {
            TypedQuery<OmapUser> q = em.createNamedQuery("OmapUser.findByRoleName", OmapUser.class);
            q.setParameter("roleName", roleName);
            return q.getResultList();
        } catch (NoResultException ex) {
            return null;
        } catch (Exception ex) {
            LoggerFactory.getLogger(OmapUserFacade.class.getName()).error("", ex);
            return null;
        }
    }
}
